#include <stdio.h>
#include <string.h>
#include <gtk/gtk.h>
#include <mysql.h>

#include "common.h"
#include "callbacks.h"
#include "interface.h"
#include "global_var.h"
#include "mysqlhelper.h"

gint delete_event(GtkWidget *widget,GdkEvent *event,gpointer user_data)
{
		g_print("拦截事件\n");
		return FALSE;
}

void destroy(GtkWidget *widget,gpointer user_data)
{
		g_print("主程序退出\n");
		gtk_main_quit();
}

void destroy_widget(GtkWidget *widget,gpointer user_data)
{
		g_print("销毁某个窗体\n");
		gtk_widget_destroy(GTK_WIDGET(widget));
		extern GtkWidget *hiden_widget;
		if(hiden_widget != NULL)
		{
				gtk_widget_show(hiden_widget);
				g_print("显示隐藏的窗口\n");
				hiden_widget = NULL;
		}
}

void hide_widget(GtkWidget *widget,gpointer user_data)
{
		g_print("隐藏某个窗体\n");
		if(widget == NULL)
		{
				return;
		}
		if(hiden_widget == NULL)
		{
				hiden_widget = widget;
				gtk_widget_hide(widget);
		}
}

void login_button_clicked(GtkWidget *widget,gpointer user_data)
{
		MYSQL conn;
		MYSQL_RES *res_ptr;
		gint res;
		gchar *tips_str;

		gchar sql[200] = {"select * from test where name='"};
		const gchar *user = gtk_entry_get_text(GTK_ENTRY(login_user_entry));
		const gchar *pwd = gtk_entry_get_text(GTK_ENTRY(login_pwd_entry));
		strcat(sql,user);
		strcat(sql,"'");
		strcat(sql," and pwd='");
		strcat(sql,pwd);
		strcat(sql,"'");

		res = query_mysql(&conn,sql);
		if(res)
		{
				res_ptr = mysql_store_result(&conn);
				if(mysql_num_rows(res_ptr) > 0)
				{
						tips_str = "登陆成功"; 
				}
				else
				{
						tips_str = "用户名或密码错误";
				}
		}
		else
		{
				if(res == 0)
				{
						tips_str = "数据库操作失败";
				}
				else
				{
						tips_str = "连接数据库失败";
				}
		}
		gtk_widget_show(create_dialog_tips(tips_str));
}

void regist_button_clicked(GtkWidget *widget,gpointer user_data)
{
		hide_widget(login_window,NULL);
		gtk_widget_show(create_regist());
}

void okbutton1_clicked(GtkWidget *widget,gpointer user_data)
{
		destroy_widget(GTK_WIDGET(user_data),NULL);
}

void regist_submit_button_clicked(GtkWidget *widget,gpointer user_data)
{
		gint res;
		gchar *tips_str;

		const gchar *user = gtk_entry_get_text(GTK_ENTRY(regist_user_entry));
		const gchar *pwd = gtk_entry_get_text(GTK_ENTRY(regist_pwd_entry));
		const gchar *pwd_again = gtk_entry_get_text(GTK_ENTRY(regist_pwd_again_entry));

		gchar sql[200] = {"insert into test values('"};
		strcat(sql,user);
		strcat(sql,"','");
		strcat(sql,pwd);
		strcat(sql,"')");
		
		if(strcmp(pwd,pwd_again) != 0)
		{
				gtk_widget_show(create_dialog_tips("两次密码不符"));
				return;
		}
		
		res = excute_mysql(sql);
		if(res)
		{
				tips_str = "注册成功";
		}
		else
		{
				if(res == 0)
				{
						tips_str = "数据库操作失败";
				}
				else
				{
						tips_str = "连接数据库失败";
				}
		}

		gtk_widget_show(create_dialog_tips(tips_str));
		if(res)
		{
				destroy_widget(regist_window,NULL);
		}
}





